package priv.dajie.tzzq.proxy;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.*;

/**
 * @ClassName ProxyPoolLocal
 * @Description
 * @Author dajie
 * @Date 2019/10/9 4:19 下午
 * @Version V1.0
 **/
public class ProxyPoolLocal{

    private Proxy[] overseasProxys = null;
    private Proxy[] localProxys = null;
    private static ProxyPoolLocal instance = null;

    public static ProxyPoolLocal getInstance(){
        if(instance==null){
            synchronized (ProxyPoolLocal.class){
                if (instance==null){
                    instance = new ProxyPoolLocal();
                }
            }
        }
        return instance;
    }

    private ProxyPoolLocal(){
        try {
            File file = new File(System.getProperty("user.dir")+ "/config/proxys.xml");
            BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
            StringBuilder stringBuilder = new StringBuilder();
            String text;
            while (true){
                text = bufferedReader.readLine();
                if (text== null){
                    break;
                }
                stringBuilder.append(text).append("\n");
            }
            Document document = Jsoup.parse(stringBuilder.toString());
            Element proxys = document.selectFirst("proxys");
            Element overseasProxysBox = proxys.selectFirst("overseas-proxy");
            Element localProxysBox = proxys.selectFirst("local-proxy");
            Elements overseas = overseasProxysBox.select("proxy");
            Elements local = localProxysBox.select("proxy");
            overseasProxys = analyzeXml(overseas);
            localProxys = analyzeXml(local);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private Proxy[] analyzeXml(Elements elements){
        Proxy[] proxies = new Proxy[elements.size()];
        for(int i=0;i<elements.size();i++){
            Element item = elements.get(i);
            if(!Boolean.parseBoolean(item.attr("enable"))){
                continue;
            }
            String ip = item.attr("ip");
            int port = Integer.parseInt(item.attr("port"));
            String type = item.attr("type");
            ProxyType proxyType = "HTTPS".equals(type)?ProxyType.HTTPS:ProxyType.HTTP;
            proxies[i] = new Proxy(ip, port, proxyType);
        }
        return proxies;
    }

    public Proxy[] getLocalProxys() {
        return localProxys;
    }

    public Proxy[] getOverseasProxys() {
        return overseasProxys;
    }

    public static void main(String[] args) {
        new ProxyPoolLocal();
    }

}
